/*
Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var signinCallback = function (result) {
  if (result.access_token) {
    var uploadVideo = new UploadVideo();
    uploadVideo.ready(result.access_token);
  } else {
    alert("access token 无效")
  }
};

var STATUS_POLLING_INTERVAL_MILLIS = 60 * 1000; // One minute.


/**
 * YouTube video uploader class
 *
 * @constructor
 */
export function UploadVideo() {
  /**
   * The array of tags for the new YouTube video.
   *
   * @attribute tags
   * @type Array.<string>
   * @default ['google-cors-upload']
   */
  this.tags = ['youtube-cors-upload'];

  /**
   * The numeric YouTube
   * [category id](https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videoCategories.list?part=snippet&regionCode=us).
   *
   * @attribute categoryId
   * @type number
   * @default 22
   */
  this.categoryId = 22;

  /**
   * The id of the new video.
   *
   * @attribute videoId
   * @type string
   * @default ''
   */
  this.videoId = '';

  this.uploadStartTime = 0;
}

import { updateYouTube } from '@/api/offer/creative'

UploadVideo.prototype.ready = function (accessToken, self) {
  this.accessToken = accessToken;
  this.gapi = gapi;
  this.authenticated = true;
  this.gapi.client.request({
    path: '/youtube/v3/channels',
    params: {
      part: 'snippet',
      mine: true
    },
    callback: function (response) {
      console.log(response)
      if (response.error) {
        self.$message.error("获取授权失败！参考信息: " + response.error.message)
      } else {
        console.log(response.items)
        if (response.items !== undefined && response.items[0] !== undefined) {
          self.$refs.nameRef.innerText = response.items[0].snippet.title
          self.$refs.srcRef.setAttribute('src', response.items[0].snippet.thumbnails.default.url)
          self.authorization = true
          self.$message.success("获取授权成功！")
        } else {
          self.$message.error("获取授权失败，请确认您的Google账号已在YouTube上注册并且有频道！")
        }
      }
    }.bind(this)
  });
  //$('#button').on("click", this.handleUploadClicked.bind(this));
};

/**
 * Uploads a video file to YouTube.
 *
 * @method uploadFile
 * @param {File} file File object corresponding to the video to upload.
 * @param self
 * @param count
 * @param creativeId
 * @param token
 */
UploadVideo.prototype.uploadFile = function (file, self, count, creativeId, token, cb) {
  let metadata = {
    snippet: {
      title: file.name,
      description: self.form.description,
      tags: this.tags,
      categoryId: this.categoryId
    },
    status: {
      privacyStatus: self.form.privacyStatus
      /*madeForKids: self.form.audience,
      selfDeclaredMadeForKids: self.form.audience*/
    }
  };
  let uploader = new MediaUploader({
    baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
    file: file,
    token: token,
    metadata: metadata,
    params: {
      part: Object.keys(metadata).join(',')
    },
    onError: function (data) {
      self.$message.error("视频上传失败, 参考信息: " + (data || '额度已满'))
      self.youTubeErrorCount++
      self.validYouTubeStatus()
    }.bind(this),
    onProgress: function (data) {
      let currentTime = Date.now();
      let bytesUploaded = data.loaded;
      let totalBytes = data.total;
      // The times are in millis, so we need to divide by 1000 to get seconds.
      let bytesPerSecond = bytesUploaded / ((currentTime - this.uploadStartTime) / 1000);
      let estimatedSecondsRemaining = (totalBytes - bytesUploaded) / bytesPerSecond;
      let percentageComplete = (bytesUploaded * 100) / totalBytes;
      /*$('#upload-progress').attr({
        value: bytesUploaded,
        max: totalBytes
      });*/
      document.getElementById(('upload-progress' + count)).setAttribute('value', bytesUploaded)
      document.getElementById(('upload-progress' + count)).setAttribute('max', totalBytes)
      //$('#percent-transferred').text(Math.floor(percentageComplete));
      document.getElementById(('percent-transferred' + count)).innerText = ('' + Math.floor(percentageComplete)) || 0
      // $('#bytes-transferred').text(bytesUploaded);
      // $('#total-bytes').text(totalBytes);
      // $('.during-upload').show();
    }.bind(this),
    onComplete: function (data) {
      //console.log(data)
      let uploadResponse = JSON.parse(data);
      let link = 'https://youtu.be/' + uploadResponse.id
      updateYouTube(creativeId, link, uploadResponse.snippet.channelId, uploadResponse.snippet.channelTitle).then(() => {
        console.log('update youTube link success!')
        self.youTubeCompleteCount++
      }).catch(() => {
        self.youTubeErrorCount++
      }).finally(() => {
        self.validYouTubeStatus()
      })
      // this.videoId = uploadResponse.id;
      //videoId: 频道里面的视频ID。 youtubeLink：https://youtu.be/videoId
      // $('#video-id').text(this.videoId);
      // $('.post-upload').show();
      //this.pollForVideoStatus();
    }.bind(this)
  });
  // This won't correspond to the *exact* start of the upload, but it should be close enough.
  this.uploadStartTime = Date.now();
  uploader.upload();
  cb&&cb(uploader)
};

UploadVideo.prototype.handleUploadClicked = function () {
  $('#button').attr('disabled', true);
  this.uploadFile($('#file').get(0).files[0]);
};

UploadVideo.prototype.pollForVideoStatus = function () {
  this.gapi.client.request({
    path: '/youtube/v3/videos',
    params: {
      part: 'status,player',
      id: this.videoId
    },
    callback: function (response) {
      if (response.error) {
        // The status polling failed.
        console.log(response.error.message);
        setTimeout(this.pollForVideoStatus.bind(this), STATUS_POLLING_INTERVAL_MILLIS);
      } else {
        var uploadStatus = response.items[0].status.uploadStatus;
        switch (uploadStatus) {
          // This is a non-final status, so we need to poll again.
          case 'uploaded':
            $('#post-upload-status').append('<li>Upload status: ' + uploadStatus + '</li>');
            setTimeout(this.pollForVideoStatus.bind(this), STATUS_POLLING_INTERVAL_MILLIS);
            break;
          // The video was successfully transcoded and is available.
          case 'processed':
            $('#player').append(response.items[0].player.embedHtml);
            $('#post-upload-status').append('<li>Final status.</li>');
            break;
          // All other statuses indicate a permanent transcoding failure.
          default:
            $('#post-upload-status').append('<li>Transcoding failed.</li>');
            break;
        }
      }
    }.bind(this)
  });
};
